
const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

exports.main = async (event, context) => {
  const db = cloud.database()
  const { typeName, name, openid } = event
  
  try {
    // 检查账本是否已存在
    const checkRes = await db.collection('accountBook')
      .where({
        name: name,
        _openid: openid
      })
      .count()
    
    if (checkRes.total > 0) {
      return { code: 400, msg: '该账本名称已存在' }
    }
    
    // 添加新账本
    const addRes = await db.collection('accountBook').add({
      data: {
        _openid: cloud.getWXContext().OPENID,
        type: typeName,
        name: name,
        createTime: db.serverDate(),
        updateTime: db.serverDate(),
        records: [],
        members: [openid]
      }
    })
    
    return { 
      code: 200, 
      data: {
        bookId: addRes._id,
        type: typeName,
        name: name
      }
    }
  } catch (err) {
    console.error(err)
    return { code: 500, msg: '服务器错误' }
  }
}